package controller;
import aop.LogData;
import aop.LogType;
import com.github.pagehelper.PageInfo;
import entity.LayRequest;
import entity.MyResult;
import entity.Role;
import entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.RoleService;
import service.UsersService;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/users")
public class UsersController{
    @Autowired
    private UsersService usersService;
    @Autowired
    private RoleService roleService;
    @LogData(logType = LogType.LOGIN,description = "登录日志")
    @RequestMapping("/login")
    public String login(String account,String password){
        Users users=usersService.selectByAccount(account);
        if (users!=null&&password.equals(users.getPassword())){
            users.setLast_login_time(new Date());
            return "/laylist.jsp";
        }
        return "/login.jsp";
    }

    @LogData(logType = LogType.LOGIN,description = "查询日志")
    @ResponseBody
    @RequestMapping("/laylist")
    public MyResult<List<Users>> list(HttpSession session,LayRequest layRequest){
        List<Role> roles=roleService.selectAll();
        session.setAttribute("role",roles);
        //执行分页查询
        PageInfo<Users> usersPageInfo = usersService.selectByPage(layRequest);
        //将分页查询结果传递到页面
        return new MyResult<>(0,usersPageInfo.getTotal(),usersPageInfo.getList());
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "add.jsp";
    }

    @LogData(logType = LogType.INSERT,description = "添加日志")
    @ResponseBody
    @RequestMapping("/add")
    public MyResult add(Users users){
        boolean insert = usersService.insert(users);
        users.setCreate_time(new Date());
        return new MyResult(0);
    }
    @LogData(logType = LogType.UPDATE,description = "删除日志")
    @ResponseBody
    @RequestMapping("/delete")
    public MyResult delete(Integer id){
        boolean delete = usersService.delete(id);
        return delete?new MyResult(200,"删除成功！")
                :new MyResult(500,"删除失败！");
    }


    @RequestMapping("/toupdate")
    public String toupdate(Integer id,ModelMap modelMap){
        Users users=usersService.selectById(id);
        modelMap.addAttribute("users",users);
        return "update.jsp";
    }
    @LogData(logType = LogType.UPDATE,description = "更新日志")
    @ResponseBody
    @RequestMapping("/update")
    public MyResult update(Users users){
        boolean update = usersService.update(users);
        return new MyResult(0);
    }

}
